package q593_validSquare;

public class Solution {
    /*
    直接强行判断
    由于给的四个点没有固定顺序 因此首先考察p1 和 p2  p1 和 p3 这两条边属于对角线还是边长
    按照不同情况考察四个边长是否相等 以及向量积是否为0

    也可以求出6条边，四条边长和两条对角线。
    边长相等的只有正方形和菱形，对角线又相等的只有正方形
    所以排序判断边长以及对角线是否相等即可
     */
    public boolean validSquare(int[] p1, int[] p2, int[] p3, int[] p4) {
        // 考察四条边的垂直和边长关系
        int x1 = p1[0], y1 = p1[1];
        int x2 = p2[0], y2 = p2[1];
        int x3 = p3[0], y3 = p3[1];
        int x4 = p4[0], y4 = p4[1];
        int t1 = (x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1);
        int t2 = (x3 - x1) * (x3 - x1) + (y3 - y1) * (y3 - y1);
        if (t1 == 0 || t2 == 0) return false;
        // 一条对角线一条边长
        if (t1 > t2) {
            int r2 = (x3 - x2) * (x3 - x2) + (y3 - y2) * (y3 - y2);
            int r3 = (x4 - x1) * (x4 - x1) + (y4 - y1) * (y4 - y1);
            int r4 = (x4 - x2) * (x4 - x2) + (y4 - y2) * (y4 - y2);

            int a1 = (x3 - x1) * (x3 - x2) + (y3 - y1) * (y3 - y2);
            int a2 = (x4 - x1) * (x4 - x2) + (y4 - y1) * (y4 - y2);
            return t2 == r2 && t2 == r3 && t2 == r4 && a1 == 0 && a2 == 0;

        } else if (t1 < t2) {
            int r2 = (x3 - x2) * (x3 - x2) + (y3 - y2) * (y3 - y2);
            int r3 = (x4 - x1) * (x4 - x1) + (y4 - y1) * (y4 - y1);
            int r4 = (x4 - x3) * (x4 - x3) + (y4 - y3) * (y4 - y3);

            int a1 = (x2 - x1) * (x2 - x3) + (y2 - y1) * (y2 - y3);
            int a2 = (x4 - x1) * (x4 - x3) + (y4 - y1) * (y4 - y3);
            return t1 == r2 && t1 == r3 && t1 == r4 && a1 == 0 && a2 == 0;
        } else {
            int r3 = (x4 - x2) * (x4 - x2) + (y4 - y2) * (y4 - y2);
            int r4 = (x4 - x3) * (x4 - x3) + (y4 - y3) * (y4 - y3);

            int a1 = (x1 - x2) * (x1 - x3) + (y1 - y2) * (y1 - y3);
            int a2 = (x4 - x2) * (x4 - x3) + (y4 - y2) * (y4 - y3);
            return t1 == r3 && t1 == r4 && a1 == 0 && a2 == 0;
        }

    }
}
